// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from '../store/modules/user.js'
import search from '../store/modules/search.js'
import tool from '@/utils/tool'
import {
  getShowProfessions,
  getAreas,
  getNavs,
  getBanners,
  getFooterEwms,
  getFooterNavs,
  getFooterLink,
} from '@/api/common_apis'
import { getWebMap } from '@/api/other'
import { getLastStudys } from '@/api/home'

import { getHomeDialog } from '@/api/new_user_activity'
Vue.use(Vuex)

export function createStore() {
  return new Vuex.Store({
    modules: {
      user,
      search
    },
    state: {
      webMapList: [], //网站地图
      activity_banner: {},
      isProfessionHome: false, //控制导航，当传true 将显示不同的导航
      // 首页banner左侧专业配置
      bannerLeftProfessions: [],
      // 底部二维码
      footerEwms: {},
      // 底部导航信息
      footerNavs: [],
      // 底部友情链接
      friendLink: [],
      // 是否展示头部导航
      isShowHeader: false,
      newUserDialog: {},
      professionData: {},
      // 获取用户学习记录
      lastStudys: [],
      isShowWhite: true, //底部footer是否显示白色白色背景
      isShowFooter: false, //是否展示footer
      isShowRightSlide: false, //是否展示右边工具栏
      isMobile: false
    },
    actions: {
      async setMobile({ store, commit }, params = {}) {
        let { isMobile } = params
        commit('setMobile', isMobile)
        return true
      },
      // 获取专业以及对应的科目
      async fetchProfessionList({ store, commit }, params = {}) {
        let res = await getShowProfessions(params).catch(err => {
          return { data: [] }
        })

        res.data &&
          Array.isArray(res.data) &&
          commit('setProfessionList', res.data)
        return true
      },
      // 获取地区
      async fetchAreaList({ store, commit }, params = {}) {
        let res = await getAreas(params).catch(err => {
          return { data: [] }
        })
        res.data && Array.isArray(res.data) && commit('setAreaList', res.data)
        return true
      },
      // 获取顶部导航
      async fetchNavs({ store, commit }, params = {}) {
        let res = await getNavs(params).catch(err => {
          return {}
        })

        console.log('fetchNavs-------');
        let { data } = res
        // 处理后台返回数据
        if (!Array.isArray(data)) return []
        data.forEach((item, index) => {
          // try {
          //   let parseJumpExtend = JSON.parse(item.jump_extend)
          //   data[index].jump_extend = parseJumpExtend || {}
          // } catch (e) {
          //   data[index].jump_extend = {}
          // }
          if (Array.isArray(item.child) && item.child.length) {
            item.child = tool.handleJumpData(item.child)
          }
        })
        commit('setNavs', data)
      },

      // 获取
      async getBannerLeftProfessions({ commit }, params = {}) {
        let { errcode, data, errmsg } = await getBanners(params).catch(err => {
          return {
            errcode: 0,
            errmsg: '',
            data: []
          }
        })
        if (+errcode !== 0) {
          data = []
        }
        // 处理连接
        data = data.map(item => {
          let { path, jump_extend, jump_type } = item
          if (+jump_type === 2) {
            item.path = `${jump_extend.jump_link}`
          } else {
            item.path = `/${item.path}/`
          }
          return item
        })
        commit('setBannerLeftProfessions', data)
      },
      // 获取底部二维码、友情链接、导航
      async getFooters({ dispatch }, params) {
        await Promise.all([
          dispatch('getFooterEwms', params),
          dispatch('getFooterNavs', params),
          dispatch('getFriendLink', params)
        ])
      },
      // 网站地图
      async getWebMap({ commit }, params) {
        try {
          let res = await getWebMap()
          if (res && Array.isArray(res.data)) {
            commit('SET_WEB_MAP_LIST', res.data)
          } else {
            commit('SET_WEB_MAP_LIST', [])
          }
        } catch (e) {
          commit('SET_WEB_MAP_LIST', [])
        }
      },
      // 获取底部二维码
      async getFooterEwms({ commit }, params) {
        let res = await getFooterEwms(params).catch(err => {
          return {
            data: {}
          }
        })
        if (+res.errcode !== 0) {
          commit('setFooterEwms', {})
        } else {
          commit('setFooterEwms', res.data)
        }
      },
      // 获取底部导航
      async getFooterNavs({ commit }, params) {
        let res = await getFooterNavs(params).catch(err => {
          return {
            data: []
          }
        })
        if (+res.errcode === 0) {
          commit('setFooterNavs', res.data)
        } else {
          commit('setFooterNavs', [])
        }
      },
      // 获取友情链接
      async getFriendLink({ commit }, params) {
        let res = await getFooterLink(params).catch(err => {
          return {
            data: []
          }
        })
        if (+res.errcode === 0) {
          commit('setFriendLink', res.data)
        } else {
          commit('setFriendLink', [])
        }
      },
      // 获取新用户弹窗信息
      async getNewUserDialog({ commit }, params) {
        let NewUserDialog = localStorage.getItem('NewUserDialog')
          ? JSON.parse(localStorage.getItem('NewUserDialog'))
          : {}
        if (
          NewUserDialog &&
          Object.keys(NewUserDialog).length &&
          NewUserDialog.expireTime >= Date.now()
        ) {
          //存在缓存
          commit('setNewUserDialog', NewUserDialog.data)
          return
        }
        let { errcode, errmsg, data } = await getHomeDialog(params).catch(
          err => {
            return { errcode: 404, errmsg: '网络错误，请重试', data: {} }
          }
        )
        if (errcode !== 0) {
          if (this.$message) this.$message({ type: 'warning', message: errmsg })
        }
        // 缓存1分钟
        let expireTime = 1 * 1 * 60 * 1000 + Date.now()
        localStorage.setItem(
          'NewUserDialog',
          JSON.stringify({ data, expireTime })
        )
        commit('setNewUserDialog', data)
      },
      // 获取学习记录
      async getLastStudys({ commit }, params = {}) {
        //
        // 先看缓存数据是否存在
        let lastStudys = localStorage.getItem('lastStudys')
          ? JSON.parse(localStorage.getItem('lastStudys'))
          : ''
        if (lastStudys && lastStudys.expireTime >= Date.now()) {
          //存在缓存
          commit('setLastStudys', lastStudys.data)
          return
        }
        let { data, errcode, errmsg } = await getLastStudys(params).catch(
          err => {
            return { errcode: 0, data: {} }
          }
        )
        if (errcode === 0) {
          let expireTime = 30 * 60 * 1000 + Date.now() //半小时缓存时间
          localStorage.setItem(
            'lastStudys',
            JSON.stringify({ data, expireTime })
          )
          commit('setLastStudys', data)
        }
      }
    },
    mutations: {
      SET_WEB_MAP_LIST(state, data) {
        state.webMapList = data
      },
      setLastStudys(state, data) {
        if (Array.isArray(data.buy) && data.buy.length) {
          data.buy =
            data.buy.filter(
              item =>
                +item.course_type < 7 ||
                +item.course_type === 16 ||
                +item.course_type === 17 ||
                +item.course_type === 19
            ) || []
        }
        state.lastStudys = data
      },
      // 设置首页banner左侧专业配置
      setBannerLeftProfessions(state, data) {
        state.bannerLeftProfessions = tool.encodeString(data)
      },
      setisProfessionHome(state, data) {
        state.isProfessionHome = data
      },
      setisShowWhite(state, data) {
        state.isShowWhite = data
      },
      setIsShowFooter(state, data) {
        state.isShowFooter = data
      },
      setNavs(state, data) {
        state.navList = tool.encodeString(data)
      },
      setMeta(state, { data, context }) {
        // 由于百度统计抓取的tkd都是默认值，所以先取消默认值配置试试
        context.title = data.title || ''
        context.keywords = data.keywords || ''
        context.description = data.description || ''
      },
      setProfessionList(state, data) {
        state.professions = data
      },
      setAreaList(state, data) {
        state.areas = data
      },
      //设置底部二维码
      setFooterEwms(state, data) {
        state.footerEwms = tool.encodeString(data)
      },
      // 设置底部导航
      setFooterNavs(state, data) {
        state.footerNavs = tool.encodeString(data)
      },
      // 设置友情链接
      setFriendLink(state, data) {
        state.friendLink = tool.encodeString(data)
      },
      // 设置新用户登录弹窗信息
      setNewUserDialog(state, data) {
        state.newUserDialog = data
      },
      setIsShowHeader(state, data) {
        state.isShowHeader = data
      },
      setIsShowRightSlide(state, data) {
        state.isShowRightSlide = data
      },
      setMobile(state, data) {
        state.isMobile = data
      },
      // 设置特殊的meta
      SET_SPECIAL_META(state, { router, context }) {
        // 获取页面的完整路径
        let { fullPath } = router
        if (tool.isObject(process.seoConfiMap)) {
          for (const key in process.seoConfiMap) {
            const item = process.seoConfiMap[key]
            if (tool.isObject(item)) {
              let { title, keywords, description, url } = item
              if (url.includes(fullPath)) {
                if (title) {
                  context.title = title
                }
                if (keywords) {
                  context.keywords = keywords
                }
                if (description) {
                  context.description = description
                }
              }
            }
          }
        }
      }
    },
    getters: {
      //专业数据
      professions: state => {
        return state.professionData.professionList
      },
      // 地区数据
      areas: state => {
        return state.professionData.areaList
      },
      // 通用导航数据
      navList: state => {
        return state.professionData.navList
      }
    }
  })
}
